void ChatRoom::join(Person* p){
string join_msg=p->name+" joins the chat";
broadcast("room", join_msg);
p->room=this;
people.push_back(p);
}
void ChatRoom::broadcast(const string& origin, const string& message){
for(auto p: people)
if(p->name != origin) p->recieve(origin, message);
}
void ChatRoom::message(const string& origin, const string& who, const string& message){
auto target=find_if(begin(people), end(people), [&](const Person* p){ return p->name==who; });
if(target!=end(people)){
(*target)->receive(origin, message);
}
}
void Person::say(const string& message) const {
room->braodcast(name, message);
}
void Person::pm(const string& who, const string& message) const {
room->message(name, who, message);
}
void Person::receive(const string& origin, const string& message){
string s{origin+": \""+message+"\""};
cout<<"["<<name<<"'s chat session] "<<s<<'\n';
chat_log.emplace_back(s);
}
ChatRoom room;
Person john{"john"};
Person jane{"jane"};
room.join(&john);
room.join(&jane);
john.say("hi room");
jane.say("oh, hey john");
Person simon("simon");
room.join(&simon);
simon.say("hi everyone!");
jane.pm("simon", "glad you could join us, simon");